import numpy as np
import os
import glob
import imageio.v2 as iio   # pip install imageio


os.chdir(os.path.dirname(__file__))

def get_raw(path,Width,Height) :
    return np.fromfile(path,dtype='uint16').reshape(Height,Width,1)

# ========= 用户参数 =========
folder = r'./hbi_id0_img'  # 原始 RAW 所在文件夹
prefix = '*.raw'           # 文件通配符
width = 3072
height = 3072
# ============================

files = sorted(glob.glob(os.path.join(folder, prefix)))
if not files:
    raise RuntimeError('目录下找不到匹配文件！')

# 用 64-bit 累加器防止溢出
acc = np.zeros((height, width), dtype=np.float64)

print(f'共 {len(files)} 张图，开始累加…')
for idx, f in enumerate(files, 1):
    # 16-bit unsigned, big-endian (ImageJ 默认导出方式)
    img = np.fromfile(f, dtype='uint16').reshape((height, width))
    acc += img
    if idx % 10 == 0 or idx == len(files):
        print(f'  {idx}/{len(files)} 已处理')

avg = (acc / len(files)).astype(np.uint16)  

avg.tofile('avg_3072x3072_16u.raw')